package controllers.similarity;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import models.EntityContainer;
import models.PropertyModel;
import models.Target;
import controllers.data.providers.Mql;
import controllers.data.providers.Sparql;


public class GraphLoader
{
    private EntityContainer              ec;
    // property -> links
    private Map<String, HashSet<String>> links;
    private Target                       source;


    public GraphLoader(EntityContainer ec, Target source)
    {
        this.ec = ec;
        links = new HashMap<>();
        this.source = source;
        getResources();
    }


    /**
     * Test function
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        EntityContainer ec1 = Mql.loadInstance("m/0345h", Target.FREEBASE);
        GraphLoader gl1 = new GraphLoader(ec1, Target.FREEBASE);
        gl1.getResources();
        System.out.println(gl1.links);
        System.out.println("#########");

        System.out.println(gl1.load(null));

        EntityContainer ec2 = Sparql.loadInstance("http://dbpedia.org/resource/Germany", Target.DBPEDIA);
        GraphLoader gl2 = new GraphLoader(ec2, Target.DBPEDIA);
        gl2.getResources();
        System.out.println(gl2.links);
        System.out.println("#########");

        System.out.println(gl2.load(null));
    }


    public EntityContainer load(PropertyModel pm)
    {
        if(pm == null)
            return null;
        EntityContainer result = null;
        Set<String> toLoad = new HashSet<>();
        String propUri = pm.getURI();
        if(links.containsKey(propUri)) {
            toLoad.addAll(links.get(propUri));
        }

        switch(source) {
            case DBPEDIA:
                for(String i : toLoad)
                    result = Sparql.loadInstance(i, source);
            break;
            case FREEBASE:
                for(String i : toLoad)
                    result = Mql.loadInstance(i, source);
            break;
            case YAGO:
            break;
            default:
                System.err.println("NYI");
            break;
        }
        return result;
    }


    private void getResources()
    {
        for(PropertyModel pm : ec.getProperties()) {
            String propertyName = pm.getURI();
            if(!pm.linkedInstances.isEmpty()) {
                HashSet<String> ls = links.get(propertyName);
                if(ls == null || ls.isEmpty())
                    ls = new HashSet<>();
                ls.addAll(pm.linkedInstances);
                links.put(propertyName, ls);
            }
        }
    }

}
